package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private DtsPermissionMapper permissionMapper;
    @Override
    public Set<String> findPermByRoleIds(Integer[] ids) {
        Set<String> permSet= new HashSet<>();
        QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id",ids);
        List<DtsPermission> permissionList = permissionMapper.selectList(queryWrapper);
        if (permissionList != null){
            for (DtsPermission dtsPermission : permissionList) {
                permSet.add(dtsPermission.getPermission());
            }
        }
        return permSet;
    }

    /**
     * 根据单个角色id查询权限字符串集合
     * @param id
     * @return
     */
    @Override
    public Set<String> findPermByRoleId(Integer id) {
        Set<String> permissions = new HashSet<>();
        if (id == null){
            return permissions;
        }

        //查询数据库
        QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", id);
        queryWrapper.eq("deleted", false);
        List<DtsPermission> permissionList = permissionMapper.selectList(queryWrapper);

        if (permissionList != null){
            for (DtsPermission dtsPermission : permissionList) {
                permissions.add(dtsPermission.getPermission());
            }
        }
        return permissions;
    }

    /**
     * 根据角色id判断是否为超级管理员权限
     * @param id
     * @return
     */
    @Override
    public boolean checkSuperPermission(Integer id) {
        if (id == null){
            return false;
        }
        QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", id);
        queryWrapper.eq("permission", "*");
        queryWrapper.eq("deleted", false);

        Integer count = permissionMapper.selectCount(queryWrapper);
        return count != 0;
    }

    /**
     * 根据角色id删除权限
     * @param id
     */
    @Override
    public void deleteByRoleId(Integer id) {
        QueryWrapper<DtsPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", id);
        queryWrapper.eq("deleted", false);

        permissionMapper.delete(queryWrapper);
    }

    /**
     * 添加权限数据
     * @param permission
     */
    @Override
    public void add(DtsPermission permission) {
        permission.setAddTime(new Date());
        permission.setUpdateTime(new Date());

        permissionMapper.insert(permission);
    }
}
